import { resources } from "cc";
import { LogMgr } from "../LogMgr";
export enum LanguageEnum{
    en= "english",
    ph = "philippines",
}
export interface ILanguage{
    refreshLanguage()
}
export class LanguageMgr{
    private static _instance: LanguageMgr;
    private _baseLanguageMap:Map<ILanguage,ILanguage> = new Map();
    /**当前语言*/
    private _currentLanguage:LanguageEnum;
    private _languageConfigData:any;//语言配置文件
    public static get instance(): LanguageMgr {
        if (!LanguageMgr._instance) {
            LanguageMgr._instance = new LanguageMgr();
        }
        return LanguageMgr._instance;
    }
    /**获取配置文件字符*/
    public getString(key:string):string{
        let string: any;
        string = this._languageConfigData[key]; 
        return string ? string : key;
    }
    /**当前语言*/
    public getCurrentLanguage():LanguageEnum{
        return this._currentLanguage;
    }
    /**设置语言*/
    public setLanguage(language:LanguageEnum):Promise<boolean>{
        return new Promise<boolean>((resolve) => {
            if(this._currentLanguage!=language)
            {
                const last:LanguageEnum = this._currentLanguage;
                this._currentLanguage = language;
                resources.load(this.getConfigUrl(language), (err, jsonAsset: any) => {
                    if(err)
                    {
                        resolve(false);
                        this._currentLanguage = last;
                        LogMgr.error("语言文件加载失败",err);
                        return;
                    }
                    if (jsonAsset && jsonAsset.json) {
                        this._languageConfigData = jsonAsset.json;
                        this.refreshUI();
                        resolve(true);
                    } else {
                        LogMgr.error("语言文件数据异常",jsonAsset);
                        this._currentLanguage = last;
                        resolve(false);
                    }
                });
            }else{
                resolve(true);
            }
        });    
    }
    public addILanguage(language:ILanguage):void{
        this._baseLanguageMap.set(language,language);
    }
    public removeILanguage(language:ILanguage):void{
        this._baseLanguageMap.delete(language);
    }
    /**根据当前语言刷新所有界面*/
    private refreshUI():void{
        this._baseLanguageMap.forEach((value)=>{
            value.refreshLanguage();
        })
    }
    private getConfigUrl(language:LanguageEnum):string{
        return "config/language/"+language;
    }
}